<?php
/*
 * @Author: 李明
 * @Date: 2021-08-25 15:43:02
 * @LastEditTime: 2022-02-08 10:33:30
 * @LastEditors: 李明
 * @Description:
 * @FilePath: /CRM2.0-PHP/app/Http/Controllers/Message/MessageController.php
 * @山东壹零贰肆信息科技有限公司
 */


namespace App\Http\Controllers\Message;

use App\Http\Controllers\common\LMReturn;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Utils;
use App\Http\Resources\MessageRecord as ResourcesMessageRecord;
use App\Models\Advance;
use App\Models\Borrower;
use App\Models\Company;
use App\Models\InterestRecord;
use App\Models\MessageModel;
use App\Models\MessageRecord;
use App\Models\Order;
use App\Models\Tag;
use App\Models\User;
use App\Models\UserTag;
use App\Models\Worker;
use GrahamCampbell\ResultType\Success;
use Illuminate\Support\Facades\Redis;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

/**
 *	@appid							      	互亿无线apiid
 *	@appkey							      	互亿无线apikey
 *	@sms_send_time						  两次短信发送时间间隔 单位：秒
 *	@sms_send_num						    最大发送次数
 *	@sms_send_black_time				限制发送时间 单位：秒 (一小时为 60*60 = 3600 秒)  目前用作 有效时间
 *	@sms_valid_time				      有效时间 单位：秒 (一小时为 60*60 = 3600 秒)
 *	@url								        接口地址
 *	@is_open_send_limit					是否开启发送限制（1开启 0关闭）
 */
$GLOBALS['ihuyi']['appid']          = env('ihuyi_appid', 'C20083820');
$GLOBALS['ihuyi']['appkey']          = env('ihuyi_appkey', '18059b86854b9348c469ba6ff3821848');
$GLOBALS['ihuyi']['sms_send_time']      = env('sms_send_time', 60);
$GLOBALS['ihuyi']['sms_send_num']      = env('sms_send_num', 5);
$GLOBALS['ihuyi']['sms_send_black_time']  = env('sms_send_black_time', 600);
$GLOBALS['ihuyi']['sms_valid_time']  = env('sms_valid_time', 600);
$GLOBALS['ihuyi']['url']          = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";
$GLOBALS['ihuyi']['is_open_send_limit']    = 1;
$GLOBALS['ihuyi']['ihuyi_sign']    =  env('ihuyi_sign', 1024);

class MessageController extends Controller
{
    /**
     * @description: 查询短信签名
     * @param {*}
     * @return {*}
     */
    public function queryMessageSign(Request $request)
    {
        try {
            //去验证token值
            $tokenInfo = json_decode($this->verifyTokenLm(), true);
            //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
            if ($tokenInfo['code'] == 400) {
                return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
            }
            $company_id = env('COMPANY', 3);
        } catch (\Throwable $th) {
            LMReturn::Error('接参发生错误', 'MCQMS1');
        }
        try {
            switch ($company_id) {
                case '1':
                    $sign_list = ['1024'];
                    break;
                case '2':
                    $sign_list = ['1024'];
                    break;
                case '3':
                    $sign_list = ['国邦盛世', '逸盛集团', '国逸控股', '安盛控股'];
                    break;
                default:
                    $sign_list = ['1024'];
                    break;
            }
            return LMReturn::Success($sign_list);
        } catch (\Throwable $th) {
            LMReturn::Error('发生了不可预知的错误', 'MCQMS2');
        }
    }
    /**
     * @description: 查询短信剩余数量
     * @param {Request} $request
     * @return {*}
     */
    public function queryMessageNum(Request $request)
    {
        try {
            //去验证token值
            $tokenInfo = json_decode($this->verifyTokenLm(), true);
            //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
            if ($tokenInfo['code'] == 400) {
                return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
            }
            $company_id = env('COMPANY', 3);
        } catch (\Throwable $th) {
            LMReturn::Error('接参发生错误', 'MCQMN1');
        }
        try {
            $where = [];
            $where[] = ['company_id', $company_id];
            $where[] = ['status', '3'];
            $msg_models = Company::find($company_id);
            $use_count = MessageRecord::where($where)->sum('count') + $msg_models->count_use;
            $nowTime = date("Y-m-d", time());
            $where_day = $where;
            $where_day[] = ['create_time', 'like', '%' . $nowTime . '%'];
            $use_count_day = MessageRecord::where($where_day)->sum('count');
            $all_count =  $msg_models->count_all;
            $current_count = $all_count - $use_count;
            $res_data['use_count'] = $use_count;
            $res_data['all_count'] = $all_count;
            $res_data['use_count_day'] = $use_count_day;
            $res_data['current_count'] = $current_count;
            return LMReturn::Success($res_data);
        } catch (\Throwable $th) {
            return LMReturn::Error('处理参数时发生错误', 'MCQMN2');
        }
    }
    /**
     * @description: 查询短信发送记录
     * @param {*}
     * @return {*}
     */
    public function queryMessageRecord(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        // 接参
        try {
            $where = [];
            $all = $request->all();
            if (isset($all['user_id'])) {
                $user_id = $all['user_id'];
                $where[] = ['user_id', $user_id];
            }
            if (isset($all['borrower_id'])) {
                $borrower_id = $all['borrower_id'];
                $where[] = ['borrower_id', $borrower_id];
            }
            if (isset($all['status'])) {
                $where[] = ['status', 'like', '%' . $all['status'] . '%'];
            }
            if (isset($all['date'])) {
                $where[] = ['date', $all['date']];
            }
            if (isset($all['phone_num'])) {
                $where[] = ['phone_num', 'like', '%' . $all['phone_num'] . '%'];
            }
            $size = isset($all['size']) ? $all['size'] : '15';
        } catch (\Throwable $th) {
            return LMReturn::Error('非法参数', 'MC003');
        }
        try {
            $where[] = ['company_id', env('COMPANY', 3)];
            $message_record_list = MessageRecord::where($where)
                ->orderBy('create_time', 'desc')
                ->paginate($size);
            $res_data = ResourcesMessageRecord::collection($message_record_list);
            $return_data = Utils::deal_page_resources($res_data, $message_record_list);
            return LMReturn::Success($return_data);
        } catch (\Throwable $th) {
            return LMReturn::Error('查询出现错误', 'MC002');
        }
    }
    /**
     * @description: 注意下面是ihuyi的短信发送结果回调
     * @param {Request} $request
     * @return {*}
     */
    public function messageSendUpdateStatus(Request $request)
    {
        $all = $request->all();
        Log::debug('注意下面是ihuyi的短信发送结果回调');
        Log::debug($all);
        try {
            $code = $all['code'];
            $msg = $all['msg'];
            $smsid = $all['smsid'];
        } catch (\Throwable $th) {
            return LMReturn::Error('非法传参');
        }

        try {
            $message_record_list = MessageRecord::where('ihuyi_id', $smsid)->get();
            if (count($message_record_list) > 0) {
                $message_record = $message_record_list[0];
            } else {
                $message_record  = new MessageRecord();
                $message_record->count = 0;
                $message_record->ihuyi_id = $smsid;
                $message_record->content = '未知的内容，计费条数需要人工处理';
            }
            $message_record->why = $msg;
            if ($code == '2') {
                $message_record->status = '3'; //1待发送 2发送中 3发送成功 4发送失败
                $count = $this->messageCountMoney($message_record->content);
                // 只有发送成功的时候，才进行计费
                $message_record->count = $count;
                $message_record->save();
                if ($message_record->message_model->type == 2) { // 如果是订单通知，在订单列表修改短信发送状态
                    $order_id = $message_record->order_id;
                    $order = Order::find($order_id);
                    $sms_status = $order->sms_status;
                    $sms_status = $sms_status + 1;
                    $order->sms_status = $sms_status;
                    $order->save();
                }
            } else {
                $message_record->status = '4'; //1待发送 2发送中 3发送成功 4发送失败
                $message_record->save();
            }
            Log::debug('短信内容是');
            Log::debug($message_record->content);
            Log::debug('计费条数是');
            Log::debug($count);
            return 'success';
        } catch (\Throwable $th) {
            return 'error';
        }
    }
    /**
     * @description: 短信计费条数
     * @param {*} $content
     * @return int
     */
    public static function messageCountMoney($content)
    {
        $count = 1;
        $countStr = MessageController::stringLength($content);
        if ($countStr > 70) {
            $count = ceil($countStr / 67); // 向上取整
        } else {
            $count = 1;
        }
        return $count;
    }
    /**
     * @description: 字数统计
     * @param string $string
     * @return int
     */
    public static function stringLength($string)
    {
        $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        preg_match_all($re['utf-8'], $string, $match);
        return count($match[0]);
    }

    /**
     * @description: 短信内容生成
     * @param {Request} $request
     * @return {*}
     */
    public function queryMessageContent(Request $request)
    {


        try {
            //去验证token值
            $tokenInfo = json_decode($this->verifyTokenLm(), true);
            //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
            if ($tokenInfo['code'] == 400) {
                return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
            }
            // 接参
            try {
                $all = $request->all();
                $id = $all['id'];
                $sms_m_id = $all['sms_model_id'];

                $record_worker_id = $tokenInfo['worker_id'];
            } catch (\Throwable $th) {
                return LMReturn::Error('非法参数', 'MCQMC1');
            }
        } catch (\Throwable $th) {
            return LMReturn::Error('处理参数时发生错误', 'MCQMC2');
        }
        try {
            $type = MessageModel::find($sms_m_id)->type;
            switch ($type) { // 1常规模板 2订单模板 3收益模板 4员工模板
                case 1:
                    $user = User::find($id);
                    $phone_num = $user->contact_manner ?? '';
                    $content = $this->messageContentCreate($sms_m_id, $user);
                    break;
                case 2:
                    $order = Order::find($id);
                    $user = $order->user;
                    $phone_num = $user->contact_manner ?? '';
                    $content = $this->messageContentCreate($sms_m_id, $user, $order);
                    break;
                case 3:
                    $interest = InterestRecord::find($id);
                    $order = $interest->order;
                    $borrower = $order->borrower ?? null;
                    $advance = $order->advance ?? null;
                    $user = $order->user;
                    $phone_num = $user->contact_manner ?? '';
                    $content = $this->messageContentCreate($sms_m_id, $user, $order, $interest, $borrower, $advance);
                    break;
                case 4:
                    $worker = Worker::find($id);
                    $phone_num = $worker->contactNum ?? '';
                    $content = $this->messageContentCreate($sms_m_id);
                    break;
                default:
                    return LMReturn::Error('发生了奇怪的错误', 'MCQMC3');
                    break;
            }
        } catch (\Throwable $th) {
            return LMReturn::Error('处理参数发生了错误', 'MCQMC4');
        }


        try {
            if ($phone_num == '') {
                return LMReturn::Error('无法获取手机号，不能够正常生成内容，请检查对应的用户是否有手机号，或者选择的模板是否正确', 'MCQMC5');
            }
            $message_record = MessageRecord::create([
                'content' => $content,
                'message_model_id' => $sms_m_id,
                'record_worker_id' => $record_worker_id,
                'count' => 0,
                'phone_num' => $phone_num,
                'company_id' => env('COMPANY', 3),/*公司1：1华鑫，2锦城，3国逸*/
                'status' => 1, // 1待发送 2发送中 3发送成功 4发送失败
                'reamrk' => '生成短信内容'
            ]);
            switch ($type) { // 1常规模板 2订单模板 3收益模板 4员工模板
                case 1:
                    $message_record->user_id = $user->id;
                    break;
                case 2:
                    $message_record->order_id = $order->id;
                    break;
                case 3:
                    $message_record->interest_id = $interest->id;
                    break;
                case 4:
                    $message_record->worker_id = $worker->id;
                    break;
                default:
                    $message_record->user_id = $user->id;
                    break;
            }
            $message_record->save();
            return LMReturn::Success($message_record, '生成短信内容成功');
        } catch (\Throwable $th) {
            return LMReturn::Error('处理数据发生了错误', 'MCQMC6');
        }
    }
    /**
     * @description: 根据传入的参数生成短信内容
     * @param {*} $message_model_id 必传 短信模板id
     * @param {*} $order 没有就传null
     * @param {*} $interest 没有就传null
     * @param {*} $user 没有就传null
     * @param {*} $borrower 没有就传null
     * @param {*} $advance 没有就传null
     * @return {*}
     */
    public function messageContentCreate($message_model_id, $user = null, $order = null, $worker = null, $interest = null, $borrower = null, $advance = null)
    {
        /*
        合同金额${orderMoney}
        还款金额${refund}
        合同编号${contractNum}
        出借人${username}
        借款人${borrower}
        垫资方${advance}
        客户经理${workername}
        生效时间${validtime}
        到期时间 ${endtime}
        签署时间${signtime}
        */

        $message = MessageModel::find($message_model_id);
        $content = $message->content;
        if ($order != null) { // 订单类
            $valid_time  = date('Y-m-d', strtotime($order->valid_time));
            $sign_time = date('Y-m-d', strtotime($order->sign_time));
            $end_time  =  date('Y-m-d', strtotime($order->contract_end_date));
            $order_money = $order->order_money ?? '';
            $contract_no = $order->contract_no ?? '';
            $content = str_replace('${orderMoney}', $order_money, $content);
            $content = str_replace('${signtime}', $sign_time, $content);
            $content = str_replace('${endtime}', $end_time, $content);
            $content = str_replace('${validtime}', $valid_time, $content);
            $content = str_replace('${contractNum}', $contract_no, $content);
            $worker_name = $order->worker->name ?? '无效人名';
            $content = str_replace('${workername}', $worker_name, $content);
            $user_name = $order->user->name ?? '无效人名';
            $content = str_replace('${username}', $user_name, $content);
            if ($borrower != null) {
                $borrower_name = $borrower->name;
            } else {
                $borrower_name = $order->borrower->name ?? '无效名称';
            }
            $content = str_replace('${borrower}', $borrower_name, $content);
            if ($advance != null) {
                $advance_name = $advance->name;
            } else {
                $advance_name = $order->advance->name ?? '无效名称';
            }
            $content = str_replace('${advance}', $advance_name, $content);
        } elseif ($user != null) { // 用户类
            $user_name = $user->name;
            $content = str_replace('${username}', $user_name, $content);
        } elseif ($worker != null) { // 员工类
            $worker_name = $worker->name;
            $content = str_replace('${workername}', $worker_name, $content);
        }
        if ($interest != null) {
            $interest_money = $interest->interest + $interest->money;
            $content = str_replace('${refund}', $interest_money, $content);
        }
        return $content;
    }

    /**
     * @description: 根据 用户标签发送 营销短信
     * @param {*}
     * @return {*}
     */
    public function messageUserTagSend(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        // 接参
        try {
            $all = $request->all();
            $tag_id = $all['tag_id'];
            $sms_m_id = $all['sms_model_id'];
            $worker_id = $tokenInfo['worker_id'];
            $sign = $all['sign'];
            $send_time  = $all['send_time'] ?? '';
        } catch (\Throwable $th) {
            return LMReturn::Error('非法参数');
        }
        $tag = Tag::find($tag_id);
        $user_list = $tag->users;
        // $tag_user_list = UserTag::where('id', '>', $id_num)->get();
        $count = 0; // 发送了多少条短信
        $message_suc_list = [];
        $message_fail_list = [];
        foreach ($user_list as $user) {
            // $user = User::find($tag_user->user_id);
            $content = $this->messageContentCreate($sms_m_id, $user);
            $mobile = $user->contact_manner;
            // $mobile = '13188887862'; //测试期间使用我自己的手机号
            // 无论是否成功都要添加记录
            $message_record = MessageRecord::create([
                'user_id' => $user->id,
                'content' => $content,
                'message_model_id' => $sms_m_id,
                'record_worker_id' => $tokenInfo['worker_id'],
                'count' => 0, // 计费条数，在发送成功之前都是0
                'status' => 1, // 1待发送 2发送中 3发送成功 4发送失败
                'remark' => '通过标签发送短信'
            ]);
            if ($mobile) {
                if ($this->sendMessage($worker_id, $content, '批量发送短信', $message_record, $mobile, $sign)) {
                    $count = $count + 1;
                    $message_record->status = 2;
                    // $message_record->count = $message_record->count + $this->messageCountMoney($content);
                    $message_record->save();
                    $message_suc_list[] = $message_record;
                } else {
                    $message_fail_list[] = $message_record;
                }
            } else {
                $message_fail_list[] = $message_record;
            }
        }
        $res_data['success'] = $message_suc_list;
        $res_data['fail'] = $message_fail_list;
        return LMReturn::Success($res_data, '成功发送' . $count . '条短信');
    }
    /**
     * @description: 根据 用户id列表发送 营销短信
     * @param {*}
     * @return {*}
     */
    public function messageUserIDSend(Request $request)
    {
        // 去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        // 判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        // 接参
        try {
            $all = $request->all();
            $user_list = $all['user_list'];
            $sms_m_id = $all['sms_model_id'];
            $worker_id = $tokenInfo['worker_id'];
        } catch (\Throwable $th) {
            return LMReturn::Error('非法参数');
        }
        $user_model_list = User::whereIn('id', $user_list)->get();
        $count = 0; //发送的总人数
        $message_suc_list = [];
        $message_fail_list = [];
        foreach ($user_model_list as $user) { // 根据用户循环发送
            $content = $this->messageContentCreate($sms_m_id, $user);
            $mobile = $user->contact_manner;
            $mobile = '13188887862'; //测试期间使用我自己的手机号
            // 无论是否成功都要添加记录
            $message_record = MessageRecord::create([
                'user_id' => $user->id,
                'content' => $content,
                'message_model_id' => $sms_m_id,
                'record_worker_id' => $tokenInfo['worker_id'],
                'count' => 0, // 计费条数，在发送成功之前都是0
                'status' => 1, // 1待发送 2发送中 3发送成功 4发送失败
                'remark' => '通过选择用户发送短信'
            ]);
            if ($mobile) {
                if ($this->sendMessage($worker_id, $content, '批量发送短信', $message_record, $mobile)) {
                    $count = $count + 1;
                    $message_record->status = 2;
                    // $message_record->count = $message_record->count + $this->messageCountMoney($content);
                    $message_record->save();
                    $message_suc_list[] = $message_record;
                } else {
                    $message_fail_list[] = $message_record;
                }
            } else {
                $message_fail_list[] = $message_record;
            }
        }
        $res_data['success'] = $message_suc_list;
        $res_data['fail'] = $message_fail_list;
        return LMReturn::Success($res_data, '成功发送' . $count . '条短信');
    }
    /**
     * @description: 根据短信记录发送短信
     * @param string $message_record_id 短信记录id
     * @return bool 是否发送成功
     */
    public function sendSmsWithType(Request $request)
    {
        try {
            // 去验证token值
            $tokenInfo = json_decode($this->verifyTokenLm(), true);
            // 判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
            if ($tokenInfo['code'] == 400) {
                return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
            }
            $all = $request->all();
            $id = $all['id'];
            $record_worker_id = $tokenInfo['worker_id'];
            $sign = $all['company'];
        } catch (\Throwable $th) {
            return LMReturn::Error('短信接参发生错误', 'MCSSWT1');
        }
        try {
            $message_record = MessageRecord::find($id);
            if ($message_record->status == 3) {
                return LMReturn::Error('该短信已经成功发送，如果要重新给客户发送短信，请重新生成内容', 'SSWT1');
            }
            $type = $message_record->message_model->type; // 1常规模板 2订单模板 3收益模板 4员工模板
            switch ($type) { // 1常规模板 2订单模板 3收益模板 4员工模板
                case 1:
                    $message_record->remark = '常规短信';
                    break;
                case 2:
                    $message_record->remark = '订单类短信';
                    break;
                case 3:
                    $message_record->remark = '收益类短信';
                    break;
                case 4:
                    $message_record->remark = '员工类短信';
                    break;
                default:
                    $message_record->remark = '常规短信';
                    break;
            }
            $message_record->save();
            $message_record = $this->newSendMessage($message_record, $record_worker_id, $sign);
            if ($message_record->status == 2) {
                return LMReturn::Success($message_record, '发送成功');
            } else {
                return LMReturn::Success($message_record, '发送失败');
            }
        } catch (\Throwable $th) {
            return LMReturn::Error('获取记录失败', 'MCSSWT2');
        }
    }
    /**
     * @description: 新版本，根据$message_record发送短信
     * @param {*} $message_record
     * @return {*}
     */
    public function newSendMessage($message_record, $record_worker_id, $sign = '1024')
    {
        if ($sign == '1024') {
            $sign = $GLOBALS['ihuyi']['ihuyi_sign'];
        }
        // 短信接口地址
        $target = $GLOBALS['ihuyi']['url'];
        $mobile = $message_record->phone_num;
        // $mobile = '13188887862'; // 测试的时候都给自己发
        $content = $message_record->content;
        $post_data = "account=" . $GLOBALS['ihuyi']['appid']
            . "&password=" . $GLOBALS['ihuyi']['appkey']
            . "&mobile=" . $mobile
            . "&content="  . rawurlencode($content)
            . '&sign=' . $sign;
        $ihuyi_data = $this->xml_to_array($this->post($post_data, $target));
        $message_record->phone_num = $mobile;
        $message_record->record_worker_id = $record_worker_id;
        $message_record->why =  $ihuyi_data['SubmitResult']['msg'];
        $message_record->company = $sign;
        if ($ihuyi_data['SubmitResult']['code'] == 2) { // 返回值为 2 时，表示发送成功
            $message_record->status = 2; // 1待发送 2发送中 3发送成功 4发送失败
            $message_record->ihuyi_id = '';
            $message_record->ihuyi_id = $ihuyi_data['SubmitResult']['smsid'];
            $message_record->save();
            Log::debug('------------------尝试调用发送短信成功，返回------------------------');
            Log::debug($ihuyi_data);
            return $message_record;
        } else {
            $message_record->status = 4; // 1待发送 2发送中 3发送成功 4发送失败
            $message_record->save();
            Log::debug('------------------尝试调用发送短信失败，返回------------------------');
            Log::debug($ihuyi_data);
            return $message_record;
        }
    }
    /**
     * @description: 发送短信接口
     * @param string $mobile
     * @param string $content
     * @param string $remark
     * @param {*} $message_record
     * @return bool
     */
    public function sendMessage($record_worker_id, $content = '', $remark = '', $message_record = null, $mobile = '15111110531', $sign = '1024')
    {
        if ($sign == '1024') {
            $sign = $GLOBALS['ihuyi']['ihuyi_sign'];
        }
        if ($message_record == null) {
            $message_record = new MessageRecord();
        }
        // 短信接口地址
        $target = $GLOBALS['ihuyi']['url'];
        // $mobile = '13188887862'; // 测试的时候都给自己发
        $post_data = "account=" . $GLOBALS['ihuyi']['appid']
            . "&password=" . $GLOBALS['ihuyi']['appkey']
            . "&mobile=" . $mobile
            . "&content="  . rawurlencode($content)
            . '&sign=' . $sign;
        // return true;
        $ihuyi_data = $this->xml_to_array($this->post($post_data, $target));
        $message_record->remark = $remark;
        $message_record->company_id =  env('COMPANY', 3);/*公司1：1华鑫，2锦城，3国逸*/
        $message_record->phone_num = $mobile;
        $message_record->record_worker_id = $record_worker_id;
        $message_record->why =  $ihuyi_data['SubmitResult']['msg'];;
        if ($ihuyi_data['SubmitResult']['code'] == 2) { // 返回值为 2 时，表示发送成功
            $message_record->status = 2; // 1待发送 2发送中 3发送成功 4发送失败
            $message_record->ihuyi_id = '';
            $message_record->ihuyi_id = $ihuyi_data['SubmitResult']['smsid'];
            $message_record->save();
            Log::debug('------------------尝试调用发送短信成功，返回------------------------');
            Log::debug($ihuyi_data);
            return true;
        } else {
            $message_record->status = 4; // 1待发送 2发送中 3发送成功 4发送失败
            $message_record->save();
            Log::debug('------------------尝试调用发送短信失败，返回------------------------');
            Log::debug($ihuyi_data);
            return false;
        }
    }
    /**
     * @description: 发送验证码接口
     * @param {Request} $request
     * @return {*}
     */
    public function send_sms_api(Request $request)
    {
        $all = $request->all();
        $mobile = $all['mobile'];
        $resutl = $this->send_sms($mobile);
        if ($request['SubmitResult']['code'] == 2) {
            return LMReturn::Success($resutl['SubmitResult'], '发送成功');
        } else {
            return LMReturn::Error($request['SubmitResult']['msg'] . '短信错误代码' . $request['SubmitResult']['code'], 'MC001');
        }
    }

    /**
     * @description: 发送短信验证码
     * @param string $mobile 手机号
     * @param string $send_code 图形验证码暂时不用
     * @return {*}
     */
    public function send_sms($mobile, $send_code = '0520')
    {
        // 短信接口地址
        $target = $GLOBALS['ihuyi']['url'];
        //获取手机号
        $mobile = $mobile;
        // //获取验证码
        // $send_code = md5($send_code);
        //生成的随机数
        $mobile_code = $this->random(4, 1);
        if (empty($mobile)) {
            exit('手机号码不能为空');
        }

        $preg = "/^1[3456789]\d{9}$/";
        if (!preg_match($preg, $mobile)) {
            exit('手机号码不正确');
        }
        // //校验图形验证码
        // if (empty($_SESSION['vcode']) or $send_code != $_SESSION['vcode']) {
        //   exit('请输入正确验证码');
        // }

        //防止恶意攻击 session 部分代码最好通过redis代替session实现
        // $this->sms_safe();

        $content = "您的验证码是：" . $mobile_code . "。请不要把验证码泄露给其他人。";
        $post_data = "account=" . $GLOBALS['ihuyi']['appid']
            . "&password=" . $GLOBALS['ihuyi']['appkey']
            . "&mobile=" . $mobile
            . "&content="  . rawurlencode($content);
        $gets = $this->xml_to_array($this->post($post_data, $target));
        if ($gets['SubmitResult']['code'] == 2) { // 返回值为 2 时，表示添加成功
            // $_SESSION['mobile']      = $mobile;
            // $_SESSION['mobile_code']  = $mobile_code;
            // $_SESSION['sms_send_time']  = time();
            // $_SESSION['sms_send_num']  += 1;
            //存入缓存
            Redis::setex($mobile, $GLOBALS['ihuyi']['sms_valid_time'], $mobile_code);
        }
        // echo $gets['SubmitResult']['msg'];
        // $data = date("Y-m-d H:i:s") . ' 返回码 : ' . $gets['SubmitResult']['code'] . ', 返回描述 : ' . $gets['SubmitResult']['msg'] . ' . 发送号码 : ' . $mobile . ' , 短信详情 : ' . $content . PHP_EOL;
        // file_put_contents($this->log_file, $data, FILE_APPEND);
        return $gets;
    }

    /**
     * @description: 将 xml数据转换为数组格式。
     * @param string $xml
     * @return {*}
     */
    public function xml_to_array($xml)
    {
        $reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
        if (preg_match_all($reg, $xml, $matches)) {
            $count = count($matches[0]);
            for ($i = 0; $i < $count; $i++) {
                $subxml = $matches[2][$i];
                $key = $matches[1][$i];
                if (preg_match($reg, $subxml)) {
                    $arr[$key] = $this->xml_to_array($subxml);
                } else {
                    $arr[$key] = $subxml;
                }
            }
        }
        return $arr;
    }
    /**
     * @description: 函数返回随机整数。
     * @param {*} $length
     * @param {*} $numeric
     * @return {*}
     */
    private function random($length = 6, $numeric = 0)
    {
        PHP_VERSION < '4.2.0' && mt_srand((float)microtime() * 1000000);
        if ($numeric) {
            $hash = sprintf('%0' . $length . 'd', mt_rand(0, pow(10, $length) - 1));
        } else {
            $hash = '';
            $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
            $max = strlen($chars) - 1;
            for ($i = 0; $i < $length; $i++) {
                $hash .= $chars[mt_rand(0, $max)];
            }
        }
        return $hash;
    }
    /**
     * @description: 防止恶意攻击 这是session 的 需要改成  redis的
     * @param {*}
     * @return {*}
     */
    private function sms_safe()
    {
        if ($GLOBALS['ihuyi']['is_open_send_limit'] != 1) {
            return;
        }
        if (!empty($_SESSION['sms_send_black']) && $_SESSION['sms_send_black'] + $GLOBALS['ihuyi']['sms_send_black_time'] > time()) {
            exit('操作频繁,请' . ceil(($_SESSION['sms_send_black'] + $GLOBALS['ihuyi']['sms_send_black_time'] - time()) / 60) . '分钟后重试');
        }

        if (empty($_SESSION['sms_send_num'])) {
            $_SESSION['sms_send_num'] = 1;
        }

        if (!empty($_SESSION['sms_send_time']) && $_SESSION['sms_send_time'] + $GLOBALS['ihuyi']['sms_send_time'] > time()) {
            exit('操作频繁,请' . ($_SESSION['sms_send_time'] + $GLOBALS['ihuyi']['sms_send_time'] - time()) . '秒后重试');
        }

        if ($_SESSION['sms_send_num'] > $GLOBALS['ihuyi']['sms_send_num']) {
            $_SESSION['sms_send_black'] = time();
            unset($_SESSION['sms_send_num']);
            unset($_SESSION['sms_send_time']);
            exit('发送次数超过限制');
        }
    }
    /**
     * @description: 请求数据到短信接口，检查环境是否 开启 curl init。
     * @param {*} $curlPost
     * @param {*} $url
     * @return {*}
     */
    public function post($curlPost, $url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_NOBODY, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        $return_str = curl_exec($curl);
        curl_close($curl);
        return $return_str;
    }

    //这里是发送验证码
    public static function SendMessageCode($phone, $Code)
    {
        $content = '您的验证码是：' . $Code . '。请不要把验证码泄露给其他人。如非本人操作，可不用理会！';
        $url = 'http://106.ihuyi.com/webservice/sms.php?method=Submit&account=' . $GLOBALS['ihuyi']['appid']
            . '&password=' . $GLOBALS['ihuyi']['appkey']
            . '&mobile=' . $phone
            . '&content=' . $content
            . '&sign=' . $GLOBALS['ihuyi']['ihuyi_sign']
            . '&format=json';
        $message = self::GetMsg($url);
        $message = json_decode($message, true);
        $code = $message['code'] ?? '';
        if ($code == 2) { // =2代表成功，等与其他直接返回原因
            //存入缓存
            Redis::setex($phone, $GLOBALS['ihuyi']['sms_valid_time'], $Code);
        }
        $message['content'] = '【' . $GLOBALS['ihuyi']['ihuyi_sign'] . '】' . $content;
        $message['phone'] = $phone;
        return $message;
    }
    // 验证码的附属方法，还没确定 作用
    public static function GetMsg($url)
    {
        //初始化： curl_init
        $ch = curl_init();
        //设置	curl_setopt
        curl_setopt($ch, CURLOPT_URL, $url);  //请求地址
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //返回数据格式
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
        //执行  curl_exec
        $result = curl_exec($ch);
        //关闭（释放）  curl_close
        curl_close($ch);
        return $result;
    }
}
